package joindemo.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import joindemo.annotation.Log;
import joindemo.common.ResponseResult;
import joindemo.common.enums.ArticleVisibilityEnum;
import joindemo.common.enums.BusinessType;
import joindemo.common.enums.HttpStatusEnum;
import joindemo.domain.query.ArticlePageQuery;
import joindemo.domain.vo.ArticleVo;
import joindemo.domain.vo.PageVo;
import joindemo.exception.ServiceException;
import joindemo.service.IArticleService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 管理员文章控制器
 * @author pym
 */
@RestController
@RequestMapping("/admin/articles")
@RequiredArgsConstructor
@Validated
@SaCheckRole("admin")
public class AdminArticleController {

    private final IArticleService articleService;

    @Operation(summary = "管理员分页查询文章")
    @Log(title = "管理员查询文章", businessType = BusinessType.SELECT)
    @GetMapping("/page")
    public ResponseResult<PageVo<ArticleVo>> page(@Valid ArticlePageQuery query) {
        query.setOnlyPublic(Boolean.FALSE);
        try {
            PageVo<ArticleVo> page = articleService.pageArticles(query);
            return ResponseResult.success(HttpStatusEnum.SUCCESS.getCode(), "管理员查询文章成功", page);
        } catch (Exception e) {
            throw new ServiceException(HttpStatusEnum.ERROR.getCode(), "查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "管理员更新文章可见性")
    @Log(title = "管理员更新文章可见性", businessType = BusinessType.UPDATE)
    @PatchMapping("/{id}/visibility")
    public ResponseResult<Void> updateVisibility(@PathVariable Integer id,
                                                 @RequestParam ArticleVisibilityEnum visibility) {
        articleService.updateArticleVisibility(id, visibility);
        return ResponseResult.success(HttpStatusEnum.SUCCESS.getCode(), "更新文章可见性成功", null);
    }

    @Operation(summary = "管理员删除文章")
    @Log(title = "管理员删除文章", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public ResponseResult<Void> deleteArticle(@PathVariable Integer id) {
        articleService.deleteArticleByAdmin(id);
        return ResponseResult.success(HttpStatusEnum.SUCCESS.getCode(), "删除文章成功", null);
    }
}